<template>
  <div class="directory">
    <div class="head">
      <div class="title"><div class="file_height_light_icon" /><div>{{ title }}</div></div>
    </div>
    <div v-loading="loading" class="file_list">
      <div class="search my-flex flex-y-center flex-x-center">
        <el-input v-model="searchKey" prefix-icon="el-icon-search" placeholder="请输入关键词进行搜索" @keyup.enter.native="onSearch" />
        <div class="add_file my-flex flex-y-center flex-x-center" @click="addGroup_visible = true">
          <div class="add_file_icon" />
        </div>
      </div>

      <el-divider />

      <el-tree
        ref="tree"
        node-key="id"
        class="filter-tree"
        highlight-current
        :data="groupDataList"
        :props="defaultProps"
        :default-expanded-keys="defaultExpandedKeys"
        :filter-node-method="filterNode"
        :current-node-key="currentNodeKey"
        :expand-on-click-node="false"
        @node-click="nodeClick"
        @node-contextmenu="rightClick"
        @node-expand="nodeExpand"
        @node-collapse="nodeCollapse"
      >
        <span
          slot-scope="{ node, data }"
          class="file_node"
          @mouseover="selectNode(node)"
          @mouseout="mouseoutNode(node)"
        >
          <span class="flex">
            <div class="file_icon" />
            <span class="textOverflow">{{ node.label }}</span>
          </span>
          <div class="my-flex">
            <span class="file_node_total">{{ data.fileTotal }}</span>
            <div v-show="node.isShowBtnGroup" class="my-flex">
              <span v-show="data.id !== 0" class="count" @click.stop="showContextMenu(data)"><i class="el-icon-more" /></span>
              <span v-show="handleIsShowAddGroup(data,node)" class="count" @click.stop="handleOpenAddGroup(data)"><div class="plus_icon" /></span>
            </div>
          </div>
        </span>
      </el-tree>
      <div v-show="showRightMenu">
        <ul id="menu" class="menu">
          <!-- <li v-if="canAddSub" class="menu__item">
            <el-button class="menu__item__button" type="text" @click="addGroup_visible = true">新增</el-button>
          </li> -->
          <li class="menu__item">
            <el-button class="menu__item__button" type="text" @click="editGroup_visible = true">修改</el-button>
          </li>
          <li v-if="canAddSub" class="menu__item">
            <el-button class="menu__item__button" type="text" @click="setOwner_visible = true">分配</el-button>
          </li>
          <li class="menu__item">
            <el-tooltip content="请先移动或删除下面所有文件" :disabled="canDelete" placement="top" effect="light">
              <span>
                <el-button class="menu__item__button" type="text" :disabled="!canDelete" @click="deleteGroup_visible = true">删除</el-button>
              </span>
            </el-tooltip>
          </li>
        </ul>
      </div>
    </div>
    <div class="footer">
      <div class="flex">
        <div class="recycleBin flex" @click="toLoadTargetData('del')">
          <div class="recycleBin_icon" :class="recycleBinCheck ? 'recycleBin_check' : ''" />
          <div class="footerText" :style="{ 'color': recycleBinCheck ? '#F96A00' : '' }">回收站</div>
        </div>
        <div class="favorites flex" @click="toLoadTargetData('star')">
          <div class="favorites_icon" :class="favoritesCheck ? 'favorites_check' : ''" />
          <div class="footerText" :style="{ 'color': favoritesCheck ? '#F96A00' : '' }">收藏夹</div>
        </div>
      </div>
    </div>
    <setOwner :visible="setOwner_visible" :check-data="checkData" @close="closeSetOwner" />
    <addGroup :visible="addGroup_visible" :check-data="checkData" @close="closeAddGroup" />
    <editGroup :visible="editGroup_visible" :check-data="checkData" @close="closeEditGroup" />
    <deleteGroup :visible="deleteGroup_visible" :check-data="checkData" @close="closeDeleteGroup" />
  </div>
</template>
<script>
import { report_group_list } from '@/api/report'

import addGroup from './addGroup-dialog.vue'
import setOwner from './setOwner-dialog.vue'
import editGroup from './editGroup-dialog.vue'
import deleteGroup from './deleteGroup-dialog.vue'

export default {
  name: 'Directory',
  components: { addGroup, editGroup, deleteGroup, setOwner },
  props: {
    title: {
      type: String,
      default: ''
    }
  },
  data() {
    // 这里存放数据
    return {
      loading: false,
      addGroup_visible: false,
      searchKey: '',
      groupDataList: [{
        id: 0,
        name: '全部分组',
        child: [],
        fileTotal: 0
      }],
      defaultProps: {
        children: 'child',
        label: 'name'
      },
      currentNodeKey: null,
      showRightMenu: false,
      setOwner_visible: false,
      editGroup_visible: false,
      deleteGroup_visible: false,
      checkData: {},
      canAddSub: false,
      canDelete: false,
      defaultExpandedKeys: [0],
      recycleBinCheck: false,
      favoritesCheck: false
    }
  },
  computed: {
  },
  // 监控data中的数据变化
  watch: {
    searchKey(val) {
      this.$refs.tree.filter(val)
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  async created() { },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.loadData()
  },
  // 生命周期 - keep-alive
  async activated() { },
  // 方法集合
  methods: {
    // 鼠标移出node节点，隐藏按钮组
    mouseoutNode(node) {
      this.$set(node, 'isShowBtnGroup', false)
    },
    // 鼠标移入node节点，显示按钮组
    selectNode(node) {
      this.$set(node, 'isShowBtnGroup', true)
    },
    // 判断是否显示新建文件夹按钮
    handleIsShowAddGroup(data, node) {
      // 不等于全部分组 并且 是一级文件夹 && 没有文件数量
      // 简单来说就是 一集目录 && 在一集目录没有报告 的情况下才能新增文件夹,可以创建多个二级目录
      const result = data.id !== 0 && data.pid === 0 && data.num === 0
      return result
    },
    // 统计所有文件数量
    handleCountAllFiles(data) {
      const arr = data
      let sum = 0

      arr.forEach(function(value) {
        sum += value.fileTotal
      })

      // console.log(sum)
      this.groupDataList[0].fileTotal = sum
    },
    // 新增文件夹
    handleOpenAddGroup(data) {
      this.checkData = data
      this.showRightMenu = false
      this.addGroup_visible = true
    },
    async loadData(reload) {
      try {
        this.loading = true
        // 说明：1：Solidity2：golang 3:linux
        const { code, data } = await report_group_list({ with: 'group_accounts.account_info', ltype: '3' })
        if (!code) {
          console.log(data)
          this.groupDataList[0].child = data

          // 统计所有文件数量
          this.handleCountAllFiles(data)

          this.$nextTick(() => {
            if (reload) {
              this.$refs.tree.setCurrentKey(this.currentNodeKey)
              this.$parent.groupChange(this.$refs.tree.getCurrentNode())
              return
            }
            this.currentNodeKey = 0
            this.$parent.groupChange({})
            this.$refs.tree.setCurrentKey(0)
          })
        }
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    // 只是简单刷新下 three ，不做太多逻辑，与父组建 onUpdateFolder 搭配使用
    async updateFolder() {
      try {
        this.loading = true
        // 说明：1：Solidity2：golang 3:linux
        const { code, data } = await report_group_list({ with: 'group_accounts.account_info', ltype: '3' })
        if (!code) {
          console.log(data)
          this.groupDataList[0].child = data

          // 统计所有文件数量
          this.handleCountAllFiles(data)
        }
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    showContextMenu(data) {
      if (!data.id) {
        return
      }
      if (data.num || data.child) {
        this.canDelete = false
      } else {
        this.canDelete = true
      }
      this.canAddSub = data.pid === 0
      this.showRightMenu = false // 先把模态框关死，目的是：第二次或者第n次右键鼠标的时候 它默认的是true
      this.showRightMenu = true
      const menu = document.querySelector('#menu')
      menu.style.left = event.clientX - 0 + 'px'
      menu.style.top = event.clientY - 10 + 'px'
      // 给整个document添加监听鼠标事件，点击任何位置执行closeRightMenu方法，及时将菜单关闭
      document.addEventListener('click', this.closeRightMenu)
      this.checkData = data
    },
    rightClick(event, data, node, obj) {
      if (!data.id) {
        return
      }
      if (data.num || data.child) {
        this.canDelete = false
      } else {
        this.canDelete = true
      }
      this.canAddSub = data.pid === 0
      this.showRightMenu = false // 先把模态框关死，目的是：第二次或者第n次右键鼠标的时候 它默认的是true
      this.showRightMenu = true
      const menu = document.querySelector('#menu')
      menu.style.left = event.clientX - 0 + 'px'
      menu.style.top = event.clientY - 10 + 'px'
      // 给整个document添加监听鼠标事件，点击任何位置执行closeRightMenu方法，及时将菜单关闭
      document.addEventListener('click', this.closeRightMenu)
      this.checkData = data
    },
    closeRightMenu() {
      this.showRightMenu = false
      // 及时关掉鼠标监听事件
      document.removeEventListener('click', this.closeRightMenu)
    },
    nodeClick(data, obj, node) {
      this.showRightMenu = false
      this.currentNodeKey = data.id
      this.$emit('groupChange', data)
      this.recycleBinCheck = false
      this.favoritesCheck = false
    },
    toLoadTargetData(target) {
      if (target === 'del') {
        this.recycleBinCheck = true
        this.favoritesCheck = false
      } else if (target === 'star') {
        this.favoritesCheck = true
        this.recycleBinCheck = false
      }
      // 取消选中节点高亮
      this.$refs.tree.setCurrentKey()
      this.$emit('groupChange', target)
    },
    nodeExpand(data) {
      // 保存当前展开的节点
      let flag = false
      this.defaultExpandedKeys.some(item => {
        if (item === data.id) { // 判断当前节点是否存在， 存在不做处理
          flag = true
          return true
        }
      })
      if (!flag) { // 不存在则存到数组里
        this.defaultExpandedKeys.push(data.id)
      }
    },
    // 树节点关闭
    nodeCollapse(data) {
      this.defaultExpandedKeys.some((item, i) => {
        if (item === data.id) {
          // 删除关闭节点
          this.defaultExpandedKeys.length = i
        }
      })
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    onSearch() {

    },
    closeAddGroup() {
      this.addGroup_visible = false
    },
    closeEditGroup() {
      this.editGroup_visible = false
    },
    closeDeleteGroup() {
      this.deleteGroup_visible = false
    },
    closeSetOwner() {
      this.setOwner_visible = false
    }
  },
  // 进入页面前
  beforeRouteEnter(to, from, next) {
    next(vm => {

    })
  },
  // 离开页面前
  beforeRouteLeave(to, from, next) {
    next()
  }
}
</script>
<style lang="scss" scoped>
.directory{
	width: 320px;
	min-height: calc(100vh - 70px);
	background-color: #FFFFFF;
  box-shadow: 0px 2px 40px 0px rgba(0, 0, 0, 0.05);
	.head{
		width: 320px;
		height: 50px;
		background: #F7F7F7;
		font-size: 16px;
		font-family: SourceHanSansCN-Regular, SourceHanSansCN;
		font-weight: 400;
		color: #000000;
		line-height: 50px;
		padding: 0 30px;
		display: flex;
		align-items: center;
		justify-content: space-between;
		.title{
			display: flex;
			align-items: center;
		}

	}
	.file_list{
		.search{
			padding: 30px 20px;
      ::v-deep .el-input__inner{
        width: 236px;
        border-radius: 30px;
        height: 35px;
        line-height: 35px;
        border: 1px solid #e4e4e4;
      }
		}

    .el-tree {
        @include FifthFont(#000000,400);

        ::v-deep .el-tree-node.is-current > .el-tree-node__content {
          font-weight: bold !important;
        }
    }

    .add_file_icon{
      width: 12px;
      height: 12px;
      background: url('../../../assets/report/add_file.png');
      background-size: 100%;
      cursor: pointer;
    }

    .add_file_icon:hover {
      background-color: #ECECEC;
    }

    .file_icon{
      width: 16px;
      height: 16px;
      background: url('../../../assets/report/file_icon.png');
      background-size: 100%;
      margin-right: 10px;
    }

    .el-divider--horizontal {
      margin: 0;
      margin-bottom: 29px;
    }

	}
  .footer {
    width: 320px;
    height: 80px;
    background: #F7F7F7;
    position: fixed;
    bottom: 0;
    padding: 32px 68px;
    .recycleBin:hover {
      cursor: pointer;
      .recycleBin_icon {
        background: url('../../../assets/report/recycleBin_hover.png');
        background-size: 100%;
      }
      .footerText {
        color: #F96A00;
      }
    }
    .favorites:hover {
      cursor: pointer;
      .favorites_icon {
        background: url('../../../assets/report/favorites_hover.png');
        background-size: 100%;
      }
      .footerText {
        color: #F96A00;
      }
    }
  }
}

.file_node {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
	padding-right: 20px;
	width: 100%;
  height: 38px;
  &_total {
    @include FifthFont(#999999,400);
    // margin-right: 4px;
    min-width: 16px;
  }
}

.count{
	font-weight: 400;
	color: #606266;
  width: 20px;
  height: 20px;
  margin-left: 2px;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  // padding-left: 1px;
}
.count:hover {
  background: #ECECEC;
}

.file_height_light_icon{
	width: 16px;
	height: 16px;
	background: url('../../../assets/report/file_height_light_icon.png');
	background-size: 100%;
	margin-right: 10px;
}
.add_file {
  width: 24px;
  height: 24px;
  background: #FAFAFA;
  border-radius: 6px;
  padding: 6px;
  cursor: pointer;
}
.recycleBin_icon {
  width: 16px;
  height: 16px;
  background: url('../../../assets/report/recycleBin.png');
  background-size: 100%;
  cursor: pointer;
  margin-right: 5px;
}

.recycleBin_check {
  background: url('../../../assets/report/recycleBin_hover.png');
  background-size: 100%;
}

.favorites_icon {
  width: 16px;
  height: 14px;
  background: url('../../../assets/report/favorites.png');
  background-size: 100%;
  cursor: pointer;
  margin-right: 5px;
}

.favorites_check {
  background: url('../../../assets/report/favorites_hover.png');
  background-size: 100%;
}

.footerText {
  font-size: 14px;
  font-family: SourceHanSansCN-Regular, SourceHanSansCN;
  font-weight: 400;
  color: #000000;
}

.textOverflow {
  width: 170px;
  overflow:hidden;
  text-overflow:ellipsis;
  white-space:nowrap;
}

.flex{
	display: flex;
  align-items: center;
  justify-content: space-between;
}

.menu__item {
  min-width: 60px;
  display: block;
  line-height: 35px;
  text-align: center;
  color: #606266;
  &__button {
      @include FifthFont(#333333,400);
  }

  .el-button.is-disabled.el-button--text {
    color: #C0C4CC;
    cursor: not-allowed;
    background-image: none;
    background-color: #FFFFFF;
    // border-color: #EBEEF5;
  }

  .el-button.is-disabled, .el-button.is-disabled:hover, .el-button.is-disabled:focus {

  }
}

.menu {
  height: auto;
  width: fit-content;
  position: absolute;
  padding: 0;
  background: #FFFFFF;
  box-shadow: 10px 0px 20px 0px rgba(0,0,0,0.07);
  border-radius: 4px;
  border: 1px solid #F2F2F2;
  z-index: 999;
}
 li:hover {
  background-color: #F8F8F8;
  cursor: pointer;
}

::v-deep .el-button--text {
  // width: 100%;
  min-width: 121px;
  // @include FifthFont(#333333,400);
}

::v-deep .el-input__inner{
	border-radius: 30px;
}

::v-deep .el-tree-node__content{
	height: 38px;
}

::v-deep .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
	font-size: 14px;
	font-family: SourceHanSansCN-Medium, SourceHanSansCN;
	font-weight: 500;
	color: #000000;
  background-color: #F7F7F7;
}

.plus_icon {
	background: url('../../../assets/linux/plus_icon.png');
  width: 16px;
  height: 16px;
  background-size: 100%;
  background-position: center;
  cursor: pointer;
  // margin-left: 4px;
}
</style>
